package com.creditease.mobile.rss.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.animation.AnimationUtils;
import android.widget.Gallery.LayoutParams;
import android.widget.*;
import android.widget.ViewSwitcher.ViewFactory;
import com.creditease.mobile.R;
import com.creditease.mobile.rss.RssConst;
import com.creditease.mobile.util.*;
import com.creditease.mobile.util.ScalingUtilities.ScalingLogic;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class ImageSwitcherActivity extends Activity implements ViewFactory {
    private RssImageSwitcher switcher;
    private String[] list;
    private GestureDetector detector;
    private int index = 0;
    private TextView imageIndex;
    private final static String TAG = ImageSwitcherActivity.class.getName();
    private AsyncImageLoader3 asyncImageLoader3 = new AsyncImageLoader3();
    private ProgressBar processbar;
    private int screenWidth;
    private int screenHeight;
    private LinearLayout layout;
    private boolean layoutVisable = true;
    private String imgDIR;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.image_switch);

        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        screenWidth = display.getWidth();
        screenHeight = display.getHeight();

        switcher = (RssImageSwitcher) findViewById(R.id.imageSwitcher);
        layout = (LinearLayout) findViewById(R.id.image_switch_bottom_layout);
        switcher.setFactory(this);
        switcher.setInAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.fade_in));
        switcher.setOutAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.fade_out));
//        switcher.setLongClickable(true);
        processbar = (ProgressBar) findViewById(R.id.image_progressbar);
        Intent intent = getIntent();
        list = intent.getExtras().getStringArray("list");
        index = intent.getExtras().getInt("index");
        String rssTitle = intent.getExtras().getString("rssTitle");
        imgDIR = intent.getExtras().getString("imgDIR");
        TextView imageTitle = (TextView) findViewById(R.id.imageTitle);
        imageIndex = (TextView) findViewById(R.id.imageIndex);
        imageTitle.setText(rssTitle);
        detector = new GestureDetector(new MySimpleGesture());

        for (int i = 0; i < list.length; i++) {
            if (i == index) {
                continue;
            }
            String path = list[i];
            if (path.startsWith("http")) {
                String newFileName = FileUtil.getFileName(path);
                // 后缀
                String filePath = imgDIR + newFileName;
                 PicDownloadUtil.add2Queue(path, filePath);
            }
        }

        // 显示图片
        showImg();
        // switcher.setLongClickable(true);
    }

    private float scale = 0;

    @Override
    public View makeView() {
        MyImageView i = new MyImageView(this, screenWidth, screenHeight, screenWidth, screenHeight);
        i.setBackgroundColor(0xFF000000);
        ImageSwitcher.LayoutParams param = new ImageSwitcher.LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,
                Gravity.CENTER);

        i.setLayoutParams(param);
        return i;
    }

    float baseValue;
    float originalScale;
    boolean isZoomTo;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        this.detector.onTouchEvent(event);

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            MyImageView imageView = (MyImageView) switcher.getSelectedView();

            baseValue = 0;
            originalScale = imageView.getScale();
            isZoomTo = false;
        }
        if (event.getAction() == MotionEvent.ACTION_MOVE) {
            if (event.getPointerCount() == 2) {
                MyImageView imageView = (MyImageView) switcher.getSelectedView();
                float x = event.getX(0) - event.getX(1);
                float y = event.getY(0) - event.getY(1);
                float value = (float) Math.sqrt(x * x + y * y);// 计算两点的距离
                // System.out.println("value:" + value);
                if (baseValue == 0) {
                    baseValue = value;
                } else {
                    float scale = value / baseValue;// 当前两点间的距离除以手指落下时两点间的距离就是需要缩放的比例。
                    // scale the image
                    imageView.zoomTo(originalScale * scale, x
                            + event.getX(1), y + event.getY(1));
                    isZoomTo = true;
                }
            }
        }
        return super.onTouchEvent(event);
    }

    //private MyImageView imageView;

    public Bitmap getBitmap4FIT(String path, int dstWidth, int dstHeight) {
        Options options = new Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);
        options.inJustDecodeBounds = false;

        dstWidth = options.outWidth;
        dstHeight = options.outHeight;
        // Part 1: Decode image
        Bitmap unscaledBitmap = ScalingUtilities.decodeFile(path, dstWidth,
                dstHeight, ScalingLogic.FIT);

        // Part 2: Scale image
        Bitmap scaledBitmap = ScalingUtilities.createScaledBitmap(
                unscaledBitmap, dstWidth, dstHeight, ScalingLogic.FIT);
        unscaledBitmap.recycle();

        return scaledBitmap;
    }

    private void showImg() {
        Log.d(TAG, "index=" + index + ",count=" + list.length);
        final String path = list[index];
        Log.d(TAG, path);
        imageIndex.setText((index + 1) + "/" + list.length);
        if (!path.startsWith("http")) {
            Log.d(TAG, "获取本地图片:" + path);
            getBitmapLocal(path);
        } else {

            String newFileName = FileUtil.getFileName(path);
            // 后缀
            final String filePath = imgDIR + newFileName;
            File file = new File(filePath);
            if (file.exists()) {
                getBitmapLocal(filePath);
            } else {
                if (!NetUtil.isNetworkAvailable(getApplicationContext())) {
                    Toast.makeText(getApplicationContext(), R.string.neterr, Toast.LENGTH_SHORT).show();
                    return;
                }
                Log.d(TAG, "获取网络图片:" + path);
                processbar.setVisibility(View.VISIBLE);

                asyncImageLoader3.loadDrawable(path,
                        new AsyncImageLoader3.ImageCallback() {
                            public void imageLoaded(Drawable imageDrawable) {
                                // is.setImageDrawable(imageDrawable);
                                if (imageDrawable != null) {
                                    // 保存图片
                                    try {

                                        BitmapDrawable bd = (BitmapDrawable) imageDrawable;
                                        Bitmap bmp = bd.getBitmap();
                                        FileOutputStream fos = new FileOutputStream(filePath);
                                        bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
                                        fos.flush();
                                        fos.close();
                                        getBitmapLocal(filePath);
                                        processbar.setVisibility(View.GONE);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        processbar.setVisibility(View.GONE);
                                        Toast.makeText(getApplication(), "图片显示异常，请检查您的网络设置", Toast.LENGTH_SHORT).show();
                                    }
                                } else {
                                    processbar.setVisibility(View.GONE);
                                    Toast.makeText(getApplication(), "图片显示异常，请检查您的网络设置", Toast.LENGTH_SHORT).show();
                                    Log.d(TAG, "index=============");
                                }
                            }
                        });
            }
        }
    }

    private Bitmap getResourceBitmap(String path, int sourceId) {
        String key = path;
        Bitmap bitmap = LruCacheUtil.getBitmapFromMemCache(key);
        if (bitmap == null) {
            Log.d(TAG, "从SD卡加载图片：" + key);
            Bitmap bitmap2 = BitmapFactory.decodeResource(getResources(), sourceId);
            LruCacheUtil.addBitmapToCache(key, bitmap2);
        } else {
            Log.d(TAG, "从缓存加载图片：" + key);
        }
        return bitmap;
    }

    private Bitmap getBitmapLocal(String path) {
        Bitmap bitmap = null;
        Log.d(TAG, "bitmap path=" + path);
        try {
            bitmap = getBitmap4FIT(path, screenWidth, screenHeight);
        } catch (Exception e) {

            String key = "nopicReader";
            bitmap = LruCacheUtil.getBitmapFromMemCache(key);
            if (bitmap == null) {
                Log.d(TAG, "从SD卡加载图片：" + key);
                bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.nopic);
                LruCacheUtil.addBitmapToCache(key, bitmap);
            } else {
                Log.d(TAG, "从缓存加载图片：" + key);
            }
        }
        switcher.setImageDrawable(bitmap, bitmap.getWidth(), bitmap.getHeight());
        View view = switcher.getSelectedView();
        Log.d(TAG, "bitmap.getWidth()=" + bitmap.getWidth()
                + ",bitmap.getHeight()=" + bitmap.getHeight());
        MyImageView imageView = (MyImageView) view;
        Log.d(TAG, "scale=" + scale + "    " + imageView.getScale());
        scale = imageView.getScale();
        imageView.zoomTo(imageView.getScaleRate(),
                screenWidth / 2, screenHeight / 2,
                100f);

        return bitmap;
    }

    private class MySimpleGesture extends SimpleOnGestureListener {
        // 按两下的第二下Touch down时触发
        public boolean onDoubleTap(MotionEvent e) {
            View view = switcher.getSelectedView();
            if (view instanceof MyImageView) {
                MyImageView imageView = (MyImageView) view;
                if (imageView.getScale() > imageView.getScaleRate()) {
                    imageView.zoomTo(imageView.getScaleRate(),
                            screenWidth / 2,
                            screenHeight / 2, 200f);
                } else {
                    imageView.zoomTo(1.5f, screenWidth / 2,
                            screenHeight / 2, 200f);
                }
            } else {

            }
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                               float velocityY) {
            if (list.length > 1) {
                if (!isZoomTo && e1.getX() - e2.getX() > 120) {
                    // 如果到达最大页
                    if ((index + 1) == list.length) {
                        index = -1;
                    }
                    index++;
                    switcher.setInAnimation(AnimationUtils.loadAnimation(getApplication(),
                            R.anim.push_left_in));
                    showImg();

//                    switcher.setOutAnimation(AnimationUtils.loadAnimation(getApplication(),
//                            android.R.anim.fade_out));
                    return true;
                }
                if (!isZoomTo && e2.getX() - e1.getX() > 120) {
                    if (index == 0) {
                        index = list.length;
                    }
                    index--;
                    switcher.setInAnimation(AnimationUtils.loadAnimation(getApplication(),
                            R.anim.push_right_in));
                    showImg();

                    /*switcher.setOutAnimation(AnimationUtils.loadAnimation(getApplication(),
                            R.anim.push_right_out));*/
                    return true;
                }
            }

            return false;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2,
                                float distanceX, float distanceY) {
            View view = switcher.getSelectedView();
            if (view instanceof MyImageView) {
                MyImageView imageView = (MyImageView) view;

                float v[] = new float[9];
                Matrix m = imageView.getImageMatrix();
                m.getValues(v);
                // 图片实时的上下左右坐标
                float left, right; // 图片的实时宽，高
                float width, height;
                width = imageView.getScale() * imageView.getImageWidth();
                height = imageView.getScale() * imageView.getImageHeight();
                // 一下逻辑为移动图片和滑动gallery换屏的逻辑。如果没对整个框架了解的非常清晰，改动以下的代码前请三思！！！！！！
                if ((int) width <= screenWidth && (int) height <= screenHeight)// 如果图片当前大小<屏幕大小，直接处理滑屏事件
                {
                    super.onScroll(e1, e2, distanceX, distanceY);
                } else {
                    left = v[Matrix.MTRANS_X];
                    right = left + width;
                    Rect r = new Rect();
                    imageView.getGlobalVisibleRect(r);

                    if (distanceX > 0)// 向左滑动
                    {
                        if (r.left > 0) {// 判断当前ImageView是否显示完全
                            super.onScroll(e1, e2, distanceX, distanceY);
                        } else if (right < screenWidth) {
                            super.onScroll(e1, e2, distanceX, distanceY);
                        } else {
                            imageView.postTranslate(-distanceX, -distanceY);
                        }
                    } else if (distanceX < 0)// 向右滑动
                    {
                        if (r.right < screenWidth) {
                            super.onScroll(e1, e2, distanceX, distanceY);
                        } else if (left > 0) {
                            super.onScroll(e1, e2, distanceX, distanceY);
                        } else {
                            imageView.postTranslate(-distanceX, -distanceY);
                        }
                    }
                }
            } else {
                return super.onScroll(e1, e2, distanceX, distanceY);
            }
            return false;
        }

        @Override
        public void onShowPress(MotionEvent e) {
            if (layoutVisable) {
                layout.setVisibility(View.GONE);
                layoutVisable = false;
            } else {
                layout.setVisibility(View.VISIBLE);
                layoutVisable = true;
            }
            super.onShowPress(e);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 1, 1, R.string.menu_saveImg);
        menu.add(0, 2, 2, R.string.menu_setting);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == 1) {
            String path = list[index];
            if (path.startsWith("http")) {
                String newFileName = FileUtil.getFileName(path);
                // 后缀
                path = imgDIR + newFileName;
            }
            File file = new File(path);

            try {
                FileInputStream fis = new FileInputStream(file);
                FileOutputStream fos = new FileOutputStream(RssConst.APPROOT
                        + file.getName() + ".jpg");

                byte[] b = new byte[4096];
                int len = 0;
                while ((len = fis.read(b)) != -1) {

                    fos.write(b, 0, len);
                }
                fos.flush();
                fos.close();
                fis.close();

                Toast.makeText(getApplicationContext(),
                        "图片已保存到：" + RssConst.APPROOT, Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "图片不存在",
                        Toast.LENGTH_LONG).show();
            }
        } else if (item.getItemId() == 2) {
            Intent intent = new Intent();
            intent.setClass(getApplicationContext(), SettingActivity.class);

            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }
}
